package org.huoran.sakamichi.main.netty.simpleTCP;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


public class TCPClient {
    private String host;
    private int port;

    private ChannelFuture channelFuture;
    private ChannelFactory factory;

    public TCPClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void start() {
        factory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
        ClientBootstrap bootstrap = new ClientBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("encode",new StringEncoder());
                pipeline.addLast("decode",new StringDecoder());
                pipeline.addLast("handler",new TCPClientHandler());
                return pipeline;
            }
        });
        bootstrap.setOption("tcpNoDelay" , true);
        bootstrap.setOption("keepAlive", true);
        channelFuture = bootstrap.connect (new InetSocketAddress(host, port));
    }

    public void send(String content){
        if(channelFuture != null){
            try{
               channelFuture.getChannel().write(content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void shutdown(){
        if(factory != null){
            factory.releaseExternalResources();
        }
    }
}